import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login/login.vue'
import Main from '../views/Main.vue'
import util from '../api/util.js'
import home from "../views/singlepage/home.vue"
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)

let appRouter = [];
if(localStorage.getItem("menuList")){
  let menuList = JSON.parse(localStorage.getItem("menuList"));
  appRouter = util.reloadMenu(menuList);
  console.log(appRouter);
}

 
const routes = [
    {
        path: '/login',
        name: 'login',
        component: login,
    },
    {
        path: '/',
        name: 'home',
        component: Main,
        redirect:"/home",
        children:[
          {
            path:"/home",
            name:"home_index",
            component:home
          },
        ]
      },
    ...appRouter
]
console.log(routes)
const router = new VueRouter({
    routes
})


router.beforeEach((to, from, next) => {
  console.log(to.name, from.name );
  
  let result = util.verifyToken(localStorage.getItem("token"));
  if(result && to.name == 'login'){
    next({
      name:"home_index"
    })
  }else if(!result && to.name != 'login'){
    next({
      name:"login"
    })
  }else{
    next();
  }
  
})
export default router